//
//  forgetPayWordViewController.m
//  dongfengTest
//
//  Created by wxt on 2021/3/18.
//

#import "ForgetPayWordViewController.h"
#import "NewPayPasswordViewController.h"
#import "ChangePassWordViewController.h"
@interface ForgetPayWordViewController ()

@property(nonatomic,strong)TKLtextFiled * verCodeF;
@property(nonatomic,strong)UIButton *getVerBtn;
@property(nonatomic,strong)UIButton * nextBtn;
@property(nonatomic,strong)UIView * messageView;
@property(nonatomic,strong)dispatch_source_t _sometimer;
@property(nonatomic,strong)NSString * phoneNum;
@property(nonatomic,strong)TKLlable * phoneNumLab;
@property(nonatomic,strong)NSString * userUID;

@end

@implementation ForgetPayWordViewController

- (void)viewDidLoad {
    [super viewDidLoad];
   
    self.view.backgroundColor = Wcolor;
    
    UIButton * backBtn =[UIButton createBtnFrame:CGRectMake(15, kStatusBarHeight+5, 18, 18) title:@"" bgImageName:@"fanhui" action:^(UIButton *button) {
        
        [self dismissViewControllerAnimated:YES completion:nil];
    }];
    [self.view addSubview:backBtn];
    TKLlable * navTit = [TKLlable labelWithFrame:CGRectMake(kWidth/2-60, kStatusBarHeight+5, 120, 20) text:@"" textColor:Bcolor font:Font_6(16) textAlignment:Textcenter backgroundColor:Ccolor];
    [self.view addSubview:navTit];
    if ([self.pushPath isEqualToString:@"payWord"]) {
        navTit.text= @"修改支付密码";
    }else if([self.pushPath isEqualToString:@"passWord"]){
        navTit.text= @"修改登录密码";
        
    }
    
    
  
  
    
    //获取用户基础信息
    [self getUserInfoUrl];
    [self addUIView];
    // Do any additional setup after loading the view.
}
-(void)addUIView{
  
   
    
    self.phoneNumLab = [TKLlable labelWithFrame:CGRectMake(20, kTopHeight+50, kWidth-40, 20) text:@"手机号" textColor:Bcolor font:Font_6(18) textAlignment:Textleft backgroundColor:Ccolor];
    [self.view addSubview:self.phoneNumLab];
    
    self.verCodeF = [TKLtextFiled FiledWithFrame:CGRectMake(30, CGRectGetMaxY(self.phoneNumLab.frame)+30,kWidth-160 , 30) text:@"请输入验证码" textColor:JhColor(51, 51, 51) font:Font_6(14) textAlignment:Textleft backgroundColor:Ccolor];
    self.verCodeF.keyboardType = UIKeyboardTypeNumberPad;
    [self.verCodeF addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    [self.view addSubview:self.verCodeF];
    
    
    UIView * linView = [[UIView alloc]initWithFrame:CGRectMake(20, CGRectGetMaxY(self.verCodeF.frame)+10, kWidth-40, 1)];
    linView.backgroundColor = JhColor(204, 204, 204);
    [self.view addSubview:linView];
    
    self.getVerBtn = [UIButton createBtnFrame:CGRectMake(CGRectGetMaxX(self.verCodeF.frame)+10, CGRectGetMaxY(self.phoneNumLab.frame)+40, 100, 20) title:@"获取验证码" bgImageName:@"" action:^(UIButton *button) {
        [self.view endEditing:YES];
        if (self.phoneNum.length > 0) {
            
            [self starTime];
            //获取验证码
            [NetRequestClass TokenAuthNetRequestGETWithRequestURL:kMessage_Send_Api WithString:self.phoneNum WithReturnValeuBlock:^(id  _Nonnull returnValue) {
                    NSLog(@"%@",returnValue);
                } WithErrorCodeBlock:^(id  _Nonnull errorCode) {
                    ;
                } WithFailureBlock:^{
                    ;
                }];
            
            self.getVerBtn.userInteractionEnabled = NO;
        }

    }];
    [self.getVerBtn setTitleColor:JhColor(153, 153, 153) forState:UIControlStateNormal];
    [self.view addSubview:self.getVerBtn];

    
    self.nextBtn = [UIButton createBtnFrame:CGRectMake(20, CGRectGetMaxY(self.getVerBtn.frame)+40, kWidth-40, 40) title:@"下一步" bgImageName:@"" action:^(UIButton *button) {
//        [self disUserCerUrl];
        [self.view endEditing:YES];
        if ([self.pushPath isEqualToString:@"payWord"]) {
            
            
            NSUserDefaults * stand = [NSUserDefaults standardUserDefaults];
            
            
            IMUser * user = [IMUser userWithUserName:[stand objectForKey:@"userName"]];
            
            if ([user deleteUser]) {
                NSLog(@"删除成功");
                //作废证书
                [self disUserCerUrl];
                
                
                
            }else{
                
                NSLog(@"删除失败");
            }

        
            
         
            
           
            NewPayPasswordViewController * newVC = [[NewPayPasswordViewController alloc]init];
            newVC.user = user;
            newVC.modalPresentationStyle = 0;
            newVC.oldPayWord = @"";
            [self presentViewController:newVC animated:YES completion:nil];
        }else if([self.pushPath isEqualToString:@"passWord"]){
            
            ChangePassWordViewController * changeVC = [[ChangePassWordViewController alloc]init];
            changeVC.modalPresentationStyle = 0;
            [self presentViewController:changeVC animated:YES completion:nil];
       
        }

    }];
    self.nextBtn.backgroundColor = JhColor(20, 122, 244);
    self.nextBtn.layer.masksToBounds = YES;
    self.nextBtn.layer.cornerRadius = 5;
    [self.view addSubview:self.nextBtn];
}
//监听长度
- (void)textFieldDidChange:(UITextField *)textField{
   
   if(textField == self.verCodeF){
        if (textField.text.length > 6) {
            self.verCodeF.text = [textField.text substringToIndex:6];
        }
        
    }
    if (textField.text.length == 6) {
        
        self.nextBtn.backgroundColor = JhColor(102, 102, 102);
        self.nextBtn.userInteractionEnabled = YES;
    }else{
        self.nextBtn.backgroundColor = JhColor(204, 204, 204);
        self.nextBtn.userInteractionEnabled = NO;
        
    }
    
    
}

- (void)starTime {
    NSTimeInterval seconds =60;
    NSDate *endTime = [NSDate dateWithTimeIntervalSinceNow:seconds];// 最后期限
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0);
    self._sometimer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER,0,0, queue);
    dispatch_source_set_timer(self._sometimer, dispatch_walltime(NULL,0),1.0*NSEC_PER_SEC,0);// 每秒执行一次
    dispatch_source_set_event_handler(self._sometimer, ^{
        int interval = [endTime timeIntervalSinceNow];
        if(interval >0) {// 更新倒计时
            NSString *timeStr = [NSString stringWithFormat:@"%ds后重新获取", interval];
            dispatch_async(dispatch_get_main_queue(), ^{

                [self.getVerBtn setTitle:timeStr forState:UIControlStateNormal];
                [self.getVerBtn setTitleColor:JhColor(153, 153, 153) forState:UIControlStateNormal];
                self.getVerBtn.userInteractionEnabled = NO;
            });
        }else{
            // 倒计时结束，关闭
            dispatch_source_cancel(self._sometimer);
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.getVerBtn setTitle:@"重新发送" forState:UIControlStateNormal];
             
                [self.getVerBtn setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
                self.getVerBtn.userInteractionEnabled = YES;
            });
        }
    });
    dispatch_resume(self._sometimer);

}
-(void)getUserInfoUrl{
    
    NSUserDefaults * stand = [NSUserDefaults standardUserDefaults];
    
    [NetRequestClass TokenAuthNetRequestGETWithRequestURL:kGetUserInfo_Api WithString:[stand objectForKey:@"userName"] WithReturnValeuBlock:^(id  _Nonnull returnValue) {
            NSLog(@"%@",returnValue);

        if ([returnValue[@"code"] intValue] == 200) {
            NSDictionary * dataDic = returnValue[@"data"];
            self.phoneNum = dataDic[@"mobile"];
            
            NSString *numberString = [self.phoneNum stringByReplacingCharactersInRange:NSMakeRange(3, 4) withString:@"****"];
            self.phoneNumLab.text = [NSString stringWithFormat:@"手机号%@",numberString];

        }

        
        } WithErrorCodeBlock:^(id  _Nonnull errorCode) {
            NSLog(@"%@",errorCode);
        } WithFailureBlock:^{
            ;
        }];
    
}
-(void)disUserCerUrl{
    NSUserDefaults * stand = [NSUserDefaults standardUserDefaults];
    [NetRequestClass TokenAuthNetRequestGETWithRequestURL:kUser_DiscardUserCer_Api WithParameter:@{@"imei":[IMSecurity getDeviceIdentifier] ,@"otptype":@"1",@"username":[stand objectForKey:@"userName"]} WithReturnValeuBlock:^(id  _Nonnull returnValue) {
        NSLog(@"%@",returnValue);
        if ([returnValue[@"code"] intValue ] ==200) {
            IMUser * user = [IMUser userWithUserName:[stand objectForKey:@"userName"]];
            [user.cert deleteCert];
            //重新获取授权码之前查询用户信安uid
            [self getUserUID];
          
            
        }else{
            
            
            
        }


        } WithErrorCodeBlock:^(id  _Nonnull errorCode) {

            [MBProgressHUD showError:@"调取接口失败" toView:self.view];
        } WithFailureBlock:^{
            ;
        }];

}
-(void)getAuthorizationCodeUrl{
    NSUserDefaults * stand = [NSUserDefaults standardUserDefaults];
    [NetRequestClass TokenAuthNetRequestGETWithRequestURL:kCertificate_RefreshCode_Api WithParameter:@{@"uid":self.userUID,@"username":[stand objectForKey:@"userName"]} WithReturnValeuBlock:^(id  _Nonnull returnValue) {
//        NSLog(@"%@",returnValue);

        if ([returnValue[@"code"] intValue] == 200) {

            NSString * getCodeStr = returnValue [@"data"];

            NSUserDefaults * stand = [NSUserDefaults standardUserDefaults];
        
            [IMUser signUpWithUserName:[stand objectForKey:@"userName"] signCode:getCodeStr andCompleteBlock:^(int resultCode, IMUser *user) {
                
             
//                NSLog(@"%d %@",resultCode,user.username);
                if (resultCode == IM_ER_SUCCESS) {
//                    NSLog(@"注册成功");
                 
                    if (![IMCert hasCertWithUsername:user.username]) {
                        NewPayPasswordViewController *payVC = [[NewPayPasswordViewController alloc]init];
                        payVC.user = user;
                        payVC.oldPayWord = self.pushPath;
                        payVC.modalPresentationStyle = 0;
                        [self presentViewController:payVC animated:YES  completion:nil];
                        
                    }else{
                      
                  
                        
                    }

                }else{
                    NSLog(@"注册失败");
                    [MBProgressHUD showMessage:@"注册失败" toView:self.view];

                }
            }];
            
        
          
        }else{
            if ([returnValue[@"code"] intValue] == 999) {
                [MBProgressHUD showError:@"获取授权失败，请联系管理员" toView:self.view];
            }else{
                [MBProgressHUD showError:returnValue[@"msg"] toView:self.view];
            }
            
        }
        
        
        } WithErrorCodeBlock:^(id  _Nonnull errorCode) {
        
            
            
            
            [MBProgressHUD showError:@"调取接口失败" toView:self.view];
        } WithFailureBlock:^{
            ;
        }];
    
    
}
-(void)getUserUID{
    NSUserDefaults * stand =[NSUserDefaults standardUserDefaults];
    
    [NetRequestClass NetRequestGETWithRequestURL:kUser_GetUserCerUID_Api WithParameter:@{@"uno":[stand objectForKey:@"userName"]} WithReturnValeuBlock:^(id  _Nonnull returnValue) {
        NSLog(@"%@",returnValue);
        if ([returnValue[@"code"] intValue] ==200) {
            
            self.userUID = [TKLTools getValueFromDic:returnValue withKey:@"data"];
            if (self.userUID.length > 0) {
                //重新获取授权码
                [self getAuthorizationCodeUrl];
            }
            
            
        }else if([returnValue[@"code"] intValue] ==999){
            [MBProgressHUD showError:@"用户不存在" toView:self.view];
            
        }
        
        
        
        
        } WithErrorCodeBlock:^(id  _Nonnull errorCode) {
            ;
        } WithFailureBlock:^{
            ;
        }];
    
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
